package com.le.medium.class4;

import org.junit.Test;

import java.util.Stack;

/**
 * 实现一个特殊的栈，在实现栈的基本功能的基础上，再实现返回栈中最小元素 的操作。
 * 要求：1.pop、push、getMin操作的时间复杂度都是O(1)；
 * 2.设计的栈类型可以 使用现成的栈结构
 */
public class Problem02_GetMinStack {

    private Stack<Integer> stack;
    private Stack<Integer> minStack ;

    public Problem02_GetMinStack() {
        this.stack = new Stack<>();
        this.minStack = new Stack<>();
    }

    public void push(Integer val){
        if (this.minStack.isEmpty()){
            this.minStack.push(val);
        }else {
            if (this.minStack.peek() >= val){
                this.minStack.push(val);
            }
        }
        this.stack.push(val);
    }

    public int pop(){
        if (this.stack.isEmpty()){
            throw new RuntimeException("stack is null");
        }
        Integer pop = this.stack.pop();
        if (pop == this.minStack.peek()){
            this.minStack.pop();
        }
        return pop;
    }

    public int getMin(){
       if (this.minStack.isEmpty()){
           throw new RuntimeException("minStack is null");
       }
       return this.minStack.peek();
    }


    @Test
    public void test(){
        Problem02_GetMinStack stack1 = new Problem02_GetMinStack();
        stack1.push(3);
        System.out.println(stack1.getMin());
        stack1.push(4);
        System.out.println(stack1.getMin());
        stack1.push(1);
        System.out.println(stack1.getMin());
        System.out.println(stack1.pop());
        System.out.println(stack1.getMin());

    }
}
